/**
 * Created by t_wolf on 1/10/2016.
 */

function initial() {
    var main_table = $("#main_table");
    main_table.html();
    $.ajax({
        url: "getStates",
        type: "GET",
        dataType: "json",
        async: false,
        success: function (data) {
            last_process = data['state_list'][data['sum'] - 1]['id'];
        }
    });
    $.ajax({
        url: "env",
        type: "GET",
        dataType: "json",
        async: false,
        success: function (data) {
            env_list = data.env_list;
            for (var i = 0; i < data.env_num; i++) {
                var env = env_list[i];
                var startButton = "";
                if (env.project == "") {
                    startButton = '<button type="button" class="btn btn-xs btn-primary" onclick="startStep($(this))">' +
                        '<label class="glyphicon glyphicon-play"></label>流程开始</button>';
                } else {
                    startButton = '<button type="button" class="btn btn-xs btn-danger" onclick="releaseStep($(this))" ' +
                        'title="直接无视流程释放环境!流程链丢失!">' +
                        '<label class="glyphicon glyphicon-exclamation-sign"></label>' +
                        '释放环境</button>';
                }
                var in_htm = '<tr class="env_info">' +
                    '<td class="first">{"id":' + env.id + ', "project":' + env.project_id + '}</td>' +
                    '<td></td>' +
                    '<td>' + env.name + '</td>' +
                    '<td>' + env.project + '</td>' +
                    '<td>' + env.user + '</td>' +
                    '<td>' + env.state_name + '</td>' +
                    '<td>' +
                    // '<button type="button" class="btn btn-xs btn-success" onclick="showHost()" ' +
                    // 'title="上传Host信息">' +
                    // '<label class="glyphicon glyphicon-open"></label>' +
                    // 'Host</button>&nbsp;' +
                    // '<button type="button" class="btn btn-xs btn-warning" onclick="showEnvSet()" ' +
                    // 'title="上传环境配置">' +
                    // '<label class="glyphicon glyphicon-open"></label>' +
                    // '配置</button>&nbsp;' +
                    startButton +
                    '</td>' +
                    '</tr>' +
                    '<tr class="env_detail">' +
                    '<td colspan="6" style="padding-bottom: 0px;">' +
                    '<div class="panel panel-warning env_status">' +
                    '<div class="panel-heading">' +
                    '<label class="panel-title" style="font-size: 14px;">环境状态</label>' +
                    '</div>' +
                    '<div class="panel-body">' +
                    '<div class="col-xs-12">' +
                    '<table class="table table-striped">' +
                    '<thead>' +
                    '<tr class="bg-success">' +
                    '<th class="first">状态ID</th>' +
                    '<th class="col-xs-3">状态名称</th>' +
                    '<th class="col-xs-3">使用者</th>' +
                    '<th class="col-xs-3">状态持续时间</th>' +
                    '<th class="col-xs-3">操作</th>' +
                    '</tr>' +
                    '</thead>' +
                    '<tbody>';
                for (var j = 0; j < env.state_list.length; j++) {
                    var isActive = "";
                    var end_time = "";
                    var opt_btn = "<td></td>";
                    var state = env.state_list[j];
                    if (state.user == undefined) {
                        state.user = "";
                    }
                    if (state.keep_time == undefined || state.keep_time == 0) {
                        state.keep_time = "";
                    }
                    if (state.keep_time != "") {
                        end_time = second_format(parseInt(state.keep_time));
                    }

                    if (state.id == env.curr_state) {
                        var process_type = 'btn-info" onclick="nextStep($(this))">' +
                            '<label class="glyphicon glyphicon-arrow-down"></label>下一流程';
                        if (state.id == last_process) {
                            process_type = 'btn-warning" onclick="endStep($(this))">' +
                                '<label class="glyphicon glyphicon-stop"></label>流程结束'
                        }
                        isActive = 'keep_time';
                        opt_btn = '<td><button type="button" class="btn btn-xs ' + process_type + '</button></td>';
                    }
                    in_htm += '<tr class="tr_status">' +
                        '<td style="display: none;">' + state.id + '</td>' +
                        '<td>' + state.name + '</td>' +
                        '<td>' + state.user + '</td>' +
                        '<td class="' + isActive + '">' + end_time + '</td>' +
                        '<td class="hide_time">' + state.keep_time + '</td>' +
                        opt_btn +
                        '</tr>';
                }
                in_htm += '</tbody>' +
                    '</table>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '</td>' + '</tr>';
                main_table.append(in_htm);
            }
            flush_number();
        }
    });

    $(".env_info").click(function () {
        var theEvent = window.event || arguments.callee.caller.arguments[0];
        var tag_env = "";
        if (theEvent.srcElement != undefined) {
            tag_env = theEvent.srcElement.tagName;
        } else {
            tag_env = theEvent.target.tagName;
        }
        // var tag_env = theEvent.srcElement.tagName ? theEvent.srcElement != undefined : theEvent.target.tagName;
        if (tag_env != "BUTTON" && tag_env != "LABEL") {
            $(this).next("tr").find(".env_status").slideToggle();
        }
    });

    setInterval(second_plus, 1000);
}


function flush_number() {
    var map_list = $("#main_table").find("tr.env_info");
    var map_length = map_list.length;
    for (var i = 0; i < map_length; i++) {
        $(map_list[i]).children(":eq(1)").text(i + 1);
    }
    second_plus();
}

function fill_zero(x) {
    if (String(x).length < 2) {
        return '0' + x;
    } else {
        return x;
    }
}

function second_format(c) {
    var d = parseInt(c / 86400);
    var h = fill_zero(parseInt(c % 86400 / 3600));
    var m = fill_zero(parseInt(c % 3600 / 60));
    var s = fill_zero(c % 60);
    return d + ' day ' + h + ':' + m + ':' + s

}

function second_plus() {
    var ht = $(".keep_time");
    for (var i = 0; i < ht.length; i++) {
        var htn = $(ht[i]).next();
        var c = parseInt($(htn).text());
        $(ht[i]).text(second_format(c + 1));
        htn.text(c + 1);
    }
}

function endStep() {
    var obj = arguments[0] || "";
    // var state = obj.parents("tr.tr_status").children(":first").text();
    var user = obj.parents("tr.tr_status").children(":eq(2)").text();
    var base = obj.parents("tr.env_detail").prev().children(":first").text();

    var req_json = JSON.parse(base);
    req_json.state = -1;
    req_json.user = user;
    req_json.encrypt = $("#encryptCode").val();

    // alert(JSON.stringify(req_json));

    $.ajax({
        url: "envUpdate",
        type: "POST",
        dataType: "json",
        data: JSON.stringify(req_json),
        async: true,
        success: function (data) {
            $.messager.confirm(data.result_code, data.result_msg, function () {
                location.reload();
            });
        }
    });
}

function nextStep() {
    var obj = arguments[0] || "";
    $("#loginwrap").dialog({
        title: "下阶段责任人"
        , 'class': "mydialog"  /*add custom class for this dialog*/
        , onClose: function () {
            $(this).dialog("close");
        }
        , buttons: [
            {
                text: "取消"
                , 'class': "btn-default"
                , click: function () {
                $(this).dialog("close");
            }
            },
            {
                text: "确定"
                , 'class': "btn-success"
                , click: function () {
                var base = obj.parents("tr.env_detail").prev().children(":first").text();
                var next_user = $("#next_user").val();
                // var next_pass = $("#next_password").val();

                var req_json = JSON.parse(base);

                if (next_user == "") {
                    $.messager.popup("下阶段责任人姓名不能为空!");
                }
                // } else if (next_pass == "") {
                //     $.messager.popup("密码不能为空!");
                // } else {
                else {
                    req_json.state = 0;
                    req_json.user = next_user;
                    // req_json.password = next_pass;
                    req_json.encrypt = $("#encryptCode").val();

                    $.ajax({
                        url: "envUpdate",
                        type: "POST",
                        dataType: "json",
                        data: JSON.stringify(req_json),
                        async: true,
                        success: function (data) {
                            $("#mask_div").hideLoading();
                            $.messager.confirm(data.result_code, data.result_msg, function () {
                                location.reload();
                            });
                        }
                    });
                    $(this).dialog("close");
                    $("#mask_div").showLoading();
                }
            }
            }
        ]
    });
}

function releaseStep() {
    var obj = arguments[0] || "";
    $.messager.model = {
        ok: {text: "确定", classed: 'btn-error'},
        cancel: {text: "取消", classed: 'btn-primary'}
    };
    $.messager.confirm("⚠️ 警告", "是否确定释放环境?此操作会终止流程链!", function () {
        var base = $(obj).parents("tr").children(":first").text();

        var req_json = JSON.parse(base);
        req_json.state = -1;
        req_json.encrypt = $("#encryptCode").val();
        req_json.user = "";

        $.ajax({
            url: "envUpdate",
            type: "POST",
            dataType: "json",
            data: JSON.stringify(req_json),
            async: true,
            success: function (data) {
                $.messager.confirm(data.result_code, data.result_msg, function () {
                    location.reload();
                });
            }
        });
    });

    return false;
}

function startStep() {
    var obj = arguments[0] || "";
    $.ajax({
        url: "getProjects",
        type: "GET",
        dataType: "json",
        async: false,
        success: function (data) {
            var pl = $("#projects_list");
            pl.html();
            for (var i = 0; i < data.sum; i++) {
                pl.append('<option value="' + data.project_list[i].id + '">' + data.project_list[i].name + '</option>');
            }
        }
    });
    $("#holdenv").dialog({
        title: "阶段责任人"
        , 'class': "mydialog"  /*add custom class for this dialog*/
        , onClose: function () {
            $(this).dialog("close");
        }
        , buttons: [
            {
                text: "取消"
                , 'class': "btn-default"
                , click: function () {
                $(this).dialog("close");
            }
            },
            {
                text: "<span class=\"ladda-label\">确定</span>"
                , 'class': "btn-success ladda-button"
                , 'data-style': "expand-right"
                , click: function () {
                var base = $(obj).parents("tr").children(":first").text();
                var hold_user = $("#hold_user").val();
                // var hold_pass = $("#hold_pass").val();
                var project_id = $("#projects_list").val();

                var req_json = JSON.parse(base);

                if (hold_user == "") {
                    $.messager.popup("阶段责任人姓名不能为空!");
                }
                // } else if (hold_pass == "") {
                //     $.messager.popup("密码不能为空!")
                else {
                    req_json.state = 0;
                    req_json.project = parseInt(project_id);
                    req_json.user = hold_user;
                    // req_json.password = hold_pass;
                    req_json.encrypt = $("#encryptCode").val();

                    // alert(JSON.stringify(req_json));

                    $.ajax({
                        url: "envUpdate",
                        type: "POST",
                        dataType: "json",
                        data: JSON.stringify(req_json),
                        async: true,
                        success: function (data) {
                            $("#mask_div").hideLoading();
                            $.messager.confirm(data.result_code, data.result_msg, function () {
                                location.reload();
                            });
                        }
                    });
                    $(this).dialog("close");
                    $("#mask_div").showLoading();
                }
            }
            }
        ]
    });
}

function showHost() {
    $.messager.popup("Not implement.");
}

function showEnvSet() {
    $.messager.popup("Not implement.");
}

function upload_file() {
    var up_btn = $("#upload-btn");
    if (up_btn.val() != "") {
        $("#upload-sub").click();
        $(".mask_div").show();
    }
}

